# coding: utf-8

# 更新成交量

import os
import set_env_path     # 请勿删除


from sqlalchemy import create_engine
from sqlalchemy.sql import text


engine = create_engine(
    os.getenv('DATABASE_URL')
    or 'mysql+pymysql://root:yuanxing@127.0.0.1/wph_www_prod?charset=utf8'
)
conn = engine.connect()


def update_user_info_bid_count():

    select_user_info_bid_count_sql = text("""
            select supplier_id,count(*) from partic where status=200 group by supplier_id;
        """)

    find_uesr_info_bid_count_sql = text("""
            select user_id from user_info where user_id=:user_id;
    """)

    find_user_id_sql = text("""
            select id from user where id=:id;
    """)

    insert_into_user_info_sql = text("""
            insert into user_info (user_id,bid_count) values (:user_id, :bid_count);
        """)

    update_user_info_sql = text("""
            update user_info set 
                bid_count = :bid_count 
            where 
                user_id = :user_id;
    """)
    records = conn.execute(select_user_info_bid_count_sql).fetchall()
    for i in records:

        user_id, bid_count = i
        print(user_id)
        user_result = conn.execute(
            find_user_id_sql,
            id=user_id,
        ).fetchone()
        if user_result:
            user_info_result = conn.execute(
                find_uesr_info_bid_count_sql,
                user_id=user_id,
            ).fetchone()
            if not user_info_result:
                conn.execute(
                    insert_into_user_info_sql,
                    bid_count=bid_count,
                    user_id=user_id,
                )
            else:
                conn.execute(
                    update_user_info_sql,
                    bid_count=bid_count,
                    user_id=user_id,
                )


if __name__ == '__main__':
    update_user_info_bid_count()